<template>
  <div>
    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-input v-model="data.username" style="width: 200px; margin-right: 10px" placeholder="请输入用户名查询"></el-input>
      <el-input v-model="data.realname" style="width: 200px; margin-right: 10px" placeholder="请输入姓名查询"></el-input>
      <el-select v-model="data.specialityId" style="width: 250px; margin-right: 10px" placeholder="请选择专业查询"
        @change="handleSpecialityChangeCard">
        <el-option v-for="item in specialityList" :key="item.specialityId" :label="item.name"
          :value="item.specialityId"></el-option>
      </el-select>

      <el-select v-model="data.classId" style="width: 250px; margin-right: 10px" placeholder="请选择班级查询">
        <el-option v-for="item in filteredClassList" :key="item.classId" :label="item.name"
          :value="item.classId"></el-option>
      </el-select>

      <!-- <el-select v-model="data.grade" style="width: 250px; margin-right: 10px" placeholder="请选择年级查询">
        <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.year" :value="item.gradeId"></el-option>
      </el-select> -->
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" style="margin-left: 10px" @click="delBatch">批量删除</el-button>
        <el-button type="info" style="margin-left: 10px">导 入</el-button>
        <el-button type="success" style="margin-left: 10px">导 出</el-button>
      </div>
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="stuId"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="姓名" prop="realname"></el-table-column>
        <el-table-column label="电话" prop="phone" show-overflow-tooltip></el-table-column>
        <el-table-column label="邮箱" prop="email" show-overflow-tooltip></el-table-column>
        <el-table-column label="所属学院" prop="collegeName" show-overflow-tooltip></el-table-column>
        <el-table-column label="所属专业" prop="specialityName" show-overflow-tooltip></el-table-column>
        <el-table-column label="所属年级" prop="gradeName" show-overflow-tooltip></el-table-column>
        <el-table-column label="所属班级" prop="className" show-overflow-tooltip></el-table-column>
        <el-table-column label="获得学分" prop="score"></el-table-column>
        <el-table-column label="角色" prop="role">
          <template #default="scope">
            <span v-if="scope.row.role === 'STUDENT'">学生</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status == 0 ? 'success' : 'danger'">
              {{ scope.row.status == 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button :icon="Edit" circle type="primary" @click="handleEdit(scope.row)"></el-button>
            <el-button :icon="Delete" circle type="danger" @click="handleDelete(scope.row.stuId)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="data.isEdit ? '编辑学生信息' : '新增学生信息'" width="600" v-model="data.formVisible"
      :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" style="padding: 20px 35px 0px 0px" :rules="data.rules" ref="formRef" label-width="120px">
        <!-- 学号 - 新增时可输入，编辑时禁用 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" :disabled="data.isEdit" />
        </el-form-item>

        <el-form-item label="姓名" prop="realname">
          <el-input v-model="data.form.realname" />
        </el-form-item>

        <!-- 关联信息下拉框 -->
        <el-form-item label="所属学院" prop="collegeId" v-if="data.isEdit">
          <el-select v-model="data.form.collegeName" placeholder="请选择学院">
            <el-option v-for="item in collegeList" :key="item.collegeId" :label="item.name" :value="item.collegeId" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属年级" prop="gradeId">
          <el-select v-model="data.form.grade" placeholder="请选择年级">
            <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.year" :value="item.gradeId" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属专业" prop="specialityId">
          <el-select v-model="data.form.specialityId" placeholder="请选择专业" @change="handleSpecialityChange">
            <el-option v-for="item in specialityList" :key="item.specialityId" :label="item.name"
              :value="item.specialityId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属班级" prop="classId">
          <el-select v-model="data.form.classId" :disabled="!data.form.specialityId" placeholder="请先选择专业">
            <el-option v-for="item in filteredClassList" :key="item.classId" :label="item.name" :value="item.classId" />
          </el-select>
        </el-form-item>

        <el-form-item label="学分" prop="score">
          <el-input v-model="data.form.score" disabled />
        </el-form-item>

        <el-form-item label="账号状态" prop="status">
          <el-radio-group v-model="data.form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select style="width: 100%" v-model="data.form.role" disabled>
            <el-option value="STUDENT" label="学生"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ data.isEdit ? '保存修改' : '新增学生' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <div class="card" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination @current-change="load" @size-change="load" v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
        :total="data.total" />
    </div>
  </div>
</template>

<script setup>
import { Delete, Edit, Search } from "@element-plus/icons-vue";
import { reactive, ref, watch, onMounted } from "vue";
import alovaInstance from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'

const formRef = ref(null);
const classList = ref([]);
const specialityList = ref([]);
const gradeList = ref([]);
const filteredClassList = ref([]);  // 过滤后的班级列表（根据专业）
const user = JSON.parse(window.localStorage.getItem("credit-system-user"));

const data = reactive({
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  form: {
    username: '',
    realname: '',
    collegeName: '',
    score: 0,
    collegeId: '',
    grade: '',
    classId: '',
    updateBy: '',
    createBy: '',
    password: ''
  },
  tableData: [],
  username: '',
  realname: '',
  collegeId: '',
  specialityId: '',
  grade: '',
  classId: '',
  ids: [],
  rules: {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    realname: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    collegeId: [
      { required: true, message: '请选择学院', trigger: 'blur' },
    ],
    specialityId: [
      { required: true, message: '请选择专业', trigger: 'blur' },
    ],
    classId: [
      { required: true, message: '请先选择专业', trigger: 'blur' },
    ],
    score: [
      { required: true, message: '请输入学分', trigger: 'blur' },
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'blur' },
    ],
    role: [
      { required: true, message: '请选择角色', trigger: 'blur' },
    ]
  }
})

// 专业选择变化处理
const handleSpecialityChange = () => {
  data.form.classId = '';  // 清空已选班级
  loadClassesBySpeciality();  // 重新加载对应专业的班级
};

const handleSpecialityChangeCard = () => {
  data.classId = '';
  loadClassesBySpecialityCard();
}

// 加载指定专业的班级数据
const loadClassesBySpecialityCard = () => {
  if (!data.specialityId) {
    filteredClassList.value = [];
    return;
  }
  alovaInstance.Get('/collegeAdminClasses/selectPage', {
    params: {
      specialityId: data.specialityId,
      collegeId: user.collegeId
    }
  }).then(res => {
    if (res.code === '200') {
      filteredClassList.value = res.data.list || [];
      console.log('加载班级数据成功:', filteredClassList.value);
    } else {
      console.log(res.msg || '获取班级数据失败');
      filteredClassList.value = [];
    }
  }).catch(error => {
    console.error('请求班级数据失败:', error);
    filteredClassList.value = [];
    ElMessage.error('获取班级信息失败，请重试');
  });
};

// 分页查询
const load = () => {
  alovaInstance.Get('/student/collegeAdminStudent/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      collegeId: user.collegeId,
      username: data.username,
      realname: data.realname,
      specialityId: data.specialityId,
      classId: data.classId,
      grade: data.grade
    }
  }).then(res => {
    data.tableData = res.data?.list
    data.total = res.data?.total
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });

  alovaInstance.Get('/collegeAdminGrade/getAllGrade', {
    params: {
      gradeId: data.gradeId
    }
  }).then(res => {
    gradeList.value = res.data || [];
  }).catch(error => {
    console.error('获取年级失败:', error);
    gradeList.value = [];  // 失败时设为空数组
    ElMessage.error('获取年级信息失败');
  });
}


// 加载指定专业的班级数据
const loadClassesBySpeciality = () => {
  if (!data.form.specialityId) {
    filteredClassList.value = [];
    return;
  }
  alovaInstance.Get('/collegeAdminClasses/selectPage', {
    params: {
      specialityId: data.form.specialityId,
      collegeId: user.collegeId
    }
  }).then(res => {
    if (res.code === '200') {
      filteredClassList.value = res.data.list || [];
      console.log('加载班级数据成功:', filteredClassList.value);
    } else {
      console.log(res.msg || '获取班级数据失败');
      filteredClassList.value = [];
    }
  }).catch(error => {
    console.error('请求班级数据失败:', error);
    filteredClassList.value = [];
    ElMessage.error(error.message || '网络错误，请稍后重试');
  });
};

// 加载专业数据
const loadSpecialities = () => {
  alovaInstance.Get('/collegeAdminSpeciality/selectSpeciality', {
    params: {
      collegeId: user.collegeId
    }
  }).then(res => {
    specialityList.value = res.data.list || [];
    console.log('专业数据加载成功:', specialityList.value);
  }).catch(error => {
    console.error('获取专业数据失败:', error);
    ElMessage.error(error.message || '网络错误，请稍后重试');
  });
};

// 监听专业选择变化
watch(() => data.form.specialityId, (newVal) => {
  if (newVal) {
    loadClassesBySpeciality();
  } else {
    filteredClassList.value = [];
    data.form.classId = '';
  }
});

watch(() => data.specialityId, (newVal) => {
  if (newVal) {
    loadClassesBySpeciality();
  } else {
    filteredClassList.value = [];
    data.classId = '';
  }
})

// 组件挂载时加载专业数据
onMounted(() => {
  loadSpecialities();
});

// 新增
const handleAdd = () => {
  data.isEdit = false;
  data.form = {
    score: 0,
    status: '0',
    role: 'STUDENT',
  }
  data.formVisible = true
}

// 编辑
const handleEdit = (row) => {
  data.isEdit = true;
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}


// 提交表单
const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (data.isEdit) {
        update();
      } else {
        add();
      }
    }
  });
}

// 新增保存
const add = () => {
  data.form.createBy = user.username
  data.form.collegeId = user.collegeId
  alovaInstance.Post('/student/collegeAdminStudent/addOneStudent', data.form).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 编辑保存
const update = () => {
  data.form.updateBy = user.username
  alovaInstance.Put('/student/collegeAdminStudent/edit', data.form).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 弹窗保存
const save = () => {
  // data.form有id就是更新，没有就是新增
  data.form.id ? update() : add()
}

// 删除
const handleDelete = (id) => {
  // 调试：打印接收到的ID
  console.log('Received ID:', id, 'Type:', typeof id);

  if (!id || id === 'undefined') {
    ElMessage.error('无效的学生ID，请刷新页面重试');
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(res => {
    alovaInstance.Put(`/student/collegeAdminStudent/delete?stuId=${id}&updateBy=${user.username}`).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
        setTimeout(() => { location.reload(); }, 500);
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(error => {
    ElMessage.error(error.message || '网络错误，请稍后重试')
  })
}

// 批量选择（保持不变）
const handleSelectionChange = (rows) => {  //返回选中的行对象数组
  console.log(rows)
  //从选中的行对象中取出所有的id，组成一个新数组！
  //使用map函数(数组内置函数)
  //遍历rows数组，将每个元素（行对象）的id属性值提取出来，组成一个新的数组。并赋值给存储id的数组中
  data.ids = rows.map(row => row.stuId)
  console.log(data.ids)
}

// 批量删除（修改URL路径）
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选中需删除的数据')
    return
  }
  ElMessageBox.confirm('批量删除数据后无法恢复，您确认删除吗？', '批量删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/student/collegeAdminStudent/deleteBatch/${user.username}`, data.ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

// 重置
const reset = () => {
  // 重置查询条件
  data.username = '';
  data.realname = '';
  data.specialityName = '';
  data.gradeName = '';
  data.className = '';
  data.grade = '';
  data.specialityId = '';
  data.classId = '';
  load()
}

// 处理文件上传的钩子
/*const handleImgSuccess = (res) => {
  data.form.avatar = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}*/

load()
</script>